<?php

function get_days_remaining_in_month($calendar, $i) {
    $numberOfDaysInMonth = $calendar[$i]->format('t');
    $dayInMonth = $calendar[$i]->format('j');
    $daysRemainingInMonth = $numberOfDaysInMonth - $dayInMonth;
    $daysRemainingInLastMonth = count($calendar) - ($i + 1);
    return $daysRemainingInLastMonth <= $daysRemainingInMonth ? $daysRemainingInLastMonth : $daysRemainingInMonth;
}

function get_days_remaining_in_week($calendar, $i) {
    $numberOfDaysInWeek = 7;
    $dayInWeek = $calendar[$i]->format('N');
    $daysRemainingInWeek = $numberOfDaysInWeek - $dayInWeek;
    $daysRemainingInLastWeek = count($calendar) - ($i + 1);
    return $daysRemainingInLastWeek <= $daysRemainingInWeek ? $daysRemainingInLastWeek : $daysRemainingInWeek;
}

function get_day_letter($calendar, $i) {
    $day = $calendar[$i]->format('D');
    return $day[0];
}

function get_displayed_duration($calendar, $i, $request) {
    $from = get_datetime_from_atom($request->from);
    $to = get_datetime_from_atom($request->to);
    $daysBeforeCalendar = $calendar[0]->diff($from);
    $daysRemainingInCalendar = count($calendar) - ($i + 1);
    $duration = $from->diff($to)->days - ($daysBeforeCalendar->invert ? $daysBeforeCalendar->days : 0);
    return ($duration <= $daysRemainingInCalendar ? $duration : $daysRemainingInCalendar) ;
}

function get_days_before_request($calendar, $i, $request) {
    $from = get_datetime_from_atom($request->from);
    $daysBeforeRequest = $calendar[$i]->diff($from);
    if ($daysBeforeRequest->invert)
        return -1;
    else
        return $daysBeforeRequest->days;
}

function format_atom_to($date, $format) {
    return get_datetime_from_atom($date)->format($format);
}

function get_datetime_from_atom($date) {
    return DateTime::createFromFormat(DateTime::ATOM, $date);
}

function starts_before($calendar, $request) {
    $from = get_datetime_from_atom($request->from);
    return $calendar[0]->diff($from)->invert == 1 && $calendar[0]->diff($from)->days != 0;
}

function ends_after($calendar, $request) {
    $to = get_datetime_from_atom($request->to);
    return $calendar[count($calendar) - 1]->diff($to)->invert != 1;
}